package junior.util;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class OrikaMapper {

    private OrikaMapper() {}
    
    private final static Set<String> EXIST_REGISTER = new HashSet<>();
    
    public static void map(Object source, Object target) {
        if (source == null || target == null) {
            return;
        }
        MapperFacade mapperFacade = getMapperFacade(source.getClass(), target.getClass());
        mapperFacade.map(source, target);
    }
    private static MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
    private static MapperFacade getMapperFacade(Class<?> sourceClass, Class<?> targetClass) {
        String cacheKey = sourceClass.getName() + "|" + targetClass.getName();
        if (!EXIST_REGISTER.contains(cacheKey)) {
            mapperFactory.classMap(sourceClass, targetClass).byDefault().register();
            EXIST_REGISTER.add(cacheKey);
        }
        return mapperFactory.getMapperFacade();
    }
}
